import com.alexmerz.graphviz.*;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;

public class EntityParser {
  private final Parser parser;
  private String path;

  EntityParser(String path) {
    parser = new Parser();
    setPath(path);
  }

  public void setPath(String path) {
    this.path = path;
  }

  public void parse(IEntity entity) {
    var array = new ArrayList<Cluster>();
    var paths = new ListGraph<String>();
    try {
      var fileReader = new FileReader(path);
      parser.parse(fileReader);

      var graphs = parser.getGraphs();
      var subGraphs = graphs.get(0).getSubgraphs();

      for (var g : subGraphs) {
        var subGraphs1 = g.getSubgraphs();
        for (var g1 : subGraphs1) {
          var cluster = new Cluster();
          var nodesLoc = g1.getNodes(false);
          var nLoc = nodesLoc.get(0);
          cluster.setName(nLoc.getId().getId());
          cluster.setDescription(nLoc.getAttribute("description"));
          var subGraphs2 = g1.getSubgraphs();
          for (var g2 : subGraphs2) {
            var category = g2.getId().getId();
            var nodesEnt = g2.getNodes(false);
            switch (category) {
              case "artefacts" -> {
                var artefacts = nodesEnt.stream().map(Cluster.Artefact::instance).toList();
                cluster.setArtefacts(artefacts);
              }
              case "furniture" -> {
                var furniture = nodesEnt.stream().map(Cluster.Furniture::instance).toList();
                cluster.setFurniture(furniture);
              }
              case "characters" -> {
                var characters = nodesEnt.stream().map(Cluster.Character::instance).toList();
                cluster.setCharacters(characters);
              }
            }
          }
          array.add(cluster);
        }
        var edges = g.getEdges();
        for (var e : edges) {
          var from = e.getSource().getNode().getId().getId();
          var to = e.getTarget().getNode().getId().getId();
          paths.addEdge(from, to);
        }
      }
    } catch (FileNotFoundException | ParseException e) {
      System.out.println(e);
    }
    entity.setLocations(array);
    entity.setPaths(paths);
  }
}
